package com.shao.commons.aspect;

import com.shao.commons.domain.Codes;
import com.shao.commons.exception.ServiceException;
import com.shao.commons.utils.AuthUtils;
import com.shao.commons.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class LoginAuthAspect {

    @Around("@annotation(com.shao.commons.aspect.annotation.GetUser)")
    public Object loginTokenParse(ProceedingJoinPoint joinPoint) {
        // 获取请求对象
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        // 解析token获取用户id
        String token = request.getHeader("Login-Token");
        Integer uid = JwtUtils.parseJwtToken(token, "uid");
        if (uid == null) {
            // 不存在返回错误，让用户重新登录
            throw new ServiceException(Codes.AUTH_ERROR);
        }
        // 存储uid
        AuthUtils.set(uid);
        try {
            // 返回用户数据
            return joinPoint.proceed();
        } catch (ServiceException e) {
            throw e;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            // 清除数据
            AuthUtils.clear();
        }
    }
}
